import { useState, useCallback, useEffect } from 'react'
import './App.css'

const BOARD_SIZE = 15
const CELL_SIZE = 36
const LINE_WIDTH = 2
const EMPTY = 0
const BLACK = 1
const WHITE = 2

type Board = number[][]
type Position = { row: number; col: number }
type GameMode = 'pvp' | 'pve'
type PlayerColor = 'black' | 'white'

function App() {
  const [board, setBoard] = useState<Board>(() => 
    Array(BOARD_SIZE).fill(null).map(() => Array(BOARD_SIZE).fill(EMPTY))
  )
  const [currentPlayer, setCurrentPlayer] = useState<number>(BLACK)
  const [winner, setWinner] = useState<number | null>(null)
  const [history, setHistory] = useState<Position[]>([])
  const [lastMove, setLastMove] = useState<Position | null>(null)
  const [gameMode, setGameMode] = useState<GameMode>('pvp')
  const [isAIThinking, setIsAIThinking] = useState(false)
  const [playerColor, setPlayerColor] = useState<PlayerColor>('black')

  // 检查是否获胜
  const checkWin = useCallback((board: Board, row: number, col: number, player: number): boolean => {
    const directions = [
      [0, 1],   // 横向
      [1, 0],   // 纵向
      [1, 1],   // 右下斜
      [1, -1],  // 左下斜
    ]

    for (const [dx, dy] of directions) {
      let count = 1

      // 正向检查
      for (let i = 1; i < 5; i++) {
        const newRow = row + dx * i
        const newCol = col + dy * i
        if (
          newRow < 0 || newRow >= BOARD_SIZE ||
          newCol < 0 || newCol >= BOARD_SIZE ||
          board[newRow][newCol] !== player
        ) break
        count++
      }

      // 反向检查
      for (let i = 1; i < 5; i++) {
        const newRow = row - dx * i
        const newCol = col - dy * i
        if (
          newRow < 0 || newRow >= BOARD_SIZE ||
          newCol < 0 || newCol >= BOARD_SIZE ||
          board[newRow][newCol] !== player
        ) break
        count++
      }

      if (count >= 5) return true
    }

    return false
  }, [])

  // 评估某个位置的分数
  const evaluatePosition = useCallback((board: Board, row: number, col: number, player: number): number => {
    let score = 0
    const directions = [
      [0, 1],   // 横向
      [1, 0],   // 纵向
      [1, 1],   // 右下斜
      [1, -1],  // 左下斜
    ]

    for (const [dx, dy] of directions) {
      let count = 1
      let blockCount = 0

      // 正向统计
      for (let i = 1; i < 5; i++) {
        const newRow = row + dx * i
        const newCol = col + dy * i
        if (newRow < 0 || newRow >= BOARD_SIZE || newCol < 0 || newCol >= BOARD_SIZE) {
          blockCount++
          break
        }
        if (board[newRow][newCol] === player) count++
        else if (board[newRow][newCol] === EMPTY) {
          break
        } else {
          blockCount++
          break
        }
      }

      // 反向统计
      for (let i = 1; i < 5; i++) {
        const newRow = row - dx * i
        const newCol = col - dy * i
        if (newRow < 0 || newRow >= BOARD_SIZE || newCol < 0 || newCol >= BOARD_SIZE) {
          blockCount++
          break
        }
        if (board[newRow][newCol] === player) count++
        else if (board[newRow][newCol] === EMPTY) {
          break
        } else {
          blockCount++
          break
        }
      }

      // 根据连子数和阻挡情况评分
      if (count >= 5) score += 100000 // 五连
      else if (count === 4) {
        if (blockCount === 0) score += 10000 // 活四
        else if (blockCount === 1) score += 1000 // 冲四
      } else if (count === 3) {
        if (blockCount === 0) score += 1000 // 活三
        else if (blockCount === 1) score += 100 // 眠三
      } else if (count === 2) {
        if (blockCount === 0) score += 100 // 活二
        else if (blockCount === 1) score += 10 // 眠二
      }
    }

    return score
  }, [])

  // AI 下棋
  const aiMove = useCallback((board: Board) => {
    let bestScore = -1
    let bestMoves: Position[] = []

    // 遍历所有空位，寻找最佳落子点
    for (let row = 0; row < BOARD_SIZE; row++) {
      for (let col = 0; col < BOARD_SIZE; col++) {
        if (board[row][col] === EMPTY) {
          // 评估进攻分数（AI自己）
          const attackScore = evaluatePosition(board, row, col, WHITE)
          // 评估防守分数（阻止玩家）
          const defenseScore = evaluatePosition(board, row, col, BLACK)
          // 综合分数，防守权重稍高
          const totalScore = attackScore + defenseScore * 1.1

          if (totalScore > bestScore) {
            bestScore = totalScore
            bestMoves = [{ row, col }]
          } else if (totalScore === bestScore) {
            bestMoves.push({ row, col })
          }
        }
      }
    }

    // 从最佳位置中随机选一个
    if (bestMoves.length > 0) {
      return bestMoves[Math.floor(Math.random() * bestMoves.length)]
    }

    // 如果没有找到，随机选一个空位
    const emptyPositions: Position[] = []
    for (let row = 0; row < BOARD_SIZE; row++) {
      for (let col = 0; col < BOARD_SIZE; col++) {
        if (board[row][col] === EMPTY) {
          emptyPositions.push({ row, col })
        }
      }
    }
    return emptyPositions[Math.floor(Math.random() * emptyPositions.length)]
  }, [evaluatePosition])

  // 执行落子
  const makeMove = useCallback((row: number, col: number, player: number) => {
    const newBoard = board.map(row => [...row])
    newBoard[row][col] = player
    setBoard(newBoard)
    setLastMove({ row, col })

    const newHistory = [...history, { row, col }]
    setHistory(newHistory)

    if (checkWin(newBoard, row, col, player)) {
      setWinner(player)
      return true
    } else {
      setCurrentPlayer(player === BLACK ? WHITE : BLACK)
      return false
    }
  }, [board, history, checkWin])

  // AI 自动下棋
  useEffect(() => {
    const aiColor = playerColor === 'black' ? WHITE : BLACK
    if (gameMode === 'pve' && currentPlayer === aiColor && !winner && !isAIThinking) {
      setIsAIThinking(true)
      // 延迟一下，让用户看到 AI 在思考
      setTimeout(() => {
        const aiPosition = aiMove(board)
        if (aiPosition) {
          makeMove(aiPosition.row, aiPosition.col, aiColor)
        }
        setIsAIThinking(false)
      }, 500)
    }
  }, [currentPlayer, gameMode, winner, board, aiMove, makeMove, isAIThinking, playerColor])

  // 玩家落子
  const handleCellClick = useCallback((row: number, col: number) => {
    if (winner || board[row][col] !== EMPTY) return
    const aiColor = playerColor === 'black' ? WHITE : BLACK
    if (gameMode === 'pve' && currentPlayer === aiColor) return // AI 回合时禁止点击
    if (isAIThinking) return

    makeMove(row, col, currentPlayer)
  }, [board, currentPlayer, winner, gameMode, makeMove, isAIThinking, playerColor])

  // 悔棋（人机对战时悔两步）
  const handleUndo = useCallback(() => {
    if (history.length === 0 || winner || isAIThinking) return

    const stepsToUndo = gameMode === 'pve' ? 2 : 1
    const actualSteps = Math.min(stepsToUndo, history.length)

    const newBoard = board.map(row => [...row])
    for (let i = 0; i < actualSteps; i++) {
      const lastPosition = history[history.length - 1 - i]
      newBoard[lastPosition.row][lastPosition.col] = EMPTY
    }
    
    setBoard(newBoard)
    const newHistory = history.slice(0, -actualSteps)
    setHistory(newHistory)
    // 悔棋后返回玩家回合
    setCurrentPlayer(playerColor === 'black' ? BLACK : WHITE)
    
    if (newHistory.length > 0) {
      setLastMove(newHistory[newHistory.length - 1])
    } else {
      setLastMove(null)
    }
  }, [board, history, winner, gameMode, isAIThinking, playerColor])

  // 重新开始
  const handleRestart = useCallback(() => {
    setBoard(Array(BOARD_SIZE).fill(null).map(() => Array(BOARD_SIZE).fill(EMPTY)))
    setCurrentPlayer(BLACK)
    setWinner(null)
    setHistory([])
    setLastMove(null)
    setIsAIThinking(false)
  }, [])

  // 切换游戏模式
  const handleModeChange = useCallback((mode: GameMode) => {
    setGameMode(mode)
    handleRestart()
  }, [handleRestart])

  // 切换玩家颜色
  const handleColorChange = useCallback((color: PlayerColor) => {
    setPlayerColor(color)
    handleRestart()
  }, [handleRestart])

  return (
    <div className="app">
      <div className="game-container">
        <h1 className="title">五子棋</h1>
        
        <div className="status-bar">
          {winner ? (
            <div className="winner-message">
              🎉 {winner === (playerColor === 'black' ? BLACK : WHITE) ? (gameMode === 'pve' ? '玩家' : (winner === BLACK ? '黑方' : '白方')) : (gameMode === 'pve' ? 'AI' : (winner === BLACK ? '黑方' : '白方'))}获胜！
            </div>
          ) : (
            <div className="current-player">
              当前回合：
              <span className={`player-indicator ${currentPlayer === BLACK ? 'black' : 'white'}`}>
                {gameMode === 'pve' 
                  ? (currentPlayer === (playerColor === 'black' ? BLACK : WHITE) 
                    ? `玩家(${playerColor === 'black' ? '黑' : '白'}方)` 
                    : `AI(${playerColor === 'black' ? '白' : '黑'}方)${isAIThinking ? ' 思考中...' : ''}`)
                  : (currentPlayer === BLACK ? '黑方' : '白方')}
              </span>
            </div>
          )}
        </div>

        <div className="mode-selector">
          <button 
            className={`mode-btn ${gameMode === 'pvp' ? 'active' : ''}`}
            onClick={() => handleModeChange('pvp')}
          >
            👥 双人对战
          </button>
          <button 
            className={`mode-btn ${gameMode === 'pve' ? 'active' : ''}`}
            onClick={() => handleModeChange('pve')}
          >
            🤖 人机对战
          </button>
        </div>

        {gameMode === 'pve' && (
          <div className="color-selector">
            <span className="color-label">选择执棋：</span>
            <button 
              className={`color-btn ${playerColor === 'black' ? 'active' : ''}`}
              onClick={() => handleColorChange('black')}
            >
              ⚫ 黑方(先手)
            </button>
            <button 
              className={`color-btn ${playerColor === 'white' ? 'active' : ''}`}
              onClick={() => handleColorChange('white')}
            >
              ⚪ 白方(后手)
            </button>
          </div>
        )}

        <div className="board-wrapper">
          <div className="board">
            {/* SVG 网格线层 */}
            <svg 
              className="board-svg" 
              width={BOARD_SIZE * CELL_SIZE} 
              height={BOARD_SIZE * CELL_SIZE}
            >
              {/* 绘制网格线 */}
              {Array.from({ length: BOARD_SIZE }).map((_, i) => (
                <g key={i}>
                  {/* 横线 */}
                  <line
                    x1={CELL_SIZE / 2}
                    y1={i * CELL_SIZE + CELL_SIZE / 2}
                    x2={(BOARD_SIZE - 1) * CELL_SIZE + CELL_SIZE / 2}
                    y2={i * CELL_SIZE + CELL_SIZE / 2}
                    stroke="#654321"
                    strokeWidth={LINE_WIDTH}
                  />
                  {/* 竖线 */}
                  <line
                    x1={i * CELL_SIZE + CELL_SIZE / 2}
                    y1={CELL_SIZE / 2}
                    x2={i * CELL_SIZE + CELL_SIZE / 2}
                    y2={(BOARD_SIZE - 1) * CELL_SIZE + CELL_SIZE / 2}
                    stroke="#654321"
                    strokeWidth={LINE_WIDTH}
                  />
                </g>
              ))}
            </svg>
            
            {/* 棋子层 */}
            <div className="board-grid">
              {board.map((row, rowIndex) => (
                <div key={rowIndex} className="board-row">
                  {row.map((cell, colIndex) => (
                    <div
                      key={`${rowIndex}-${colIndex}`}
                      className="cell"
                      onClick={() => handleCellClick(rowIndex, colIndex)}
                    >
                      {cell !== EMPTY && (
                        <div className={`piece ${cell === BLACK ? 'black' : 'white'}`}>
                          {lastMove?.row === rowIndex && lastMove?.col === colIndex && (
                            <div className="last-move-marker"></div>
                          )}
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className="controls">
          <button 
            className="btn btn-undo" 
            onClick={handleUndo}
            disabled={history.length === 0 || winner !== null || isAIThinking}
          >
            ↶ 悔棋{gameMode === 'pve' && history.length > 0 ? '(两步)' : ''}
          </button>
          <button className="btn btn-restart" onClick={handleRestart}>
            ⟲ 重新开始
          </button>
        </div>

        <div className="info">
          <p>📝 游戏规则：</p>
          <ul>
            <li>{gameMode === 'pvp' ? '黑方先行，双方轮流落子' : `${playerColor === 'black' ? '玩家执黑先行' : 'AI执黑先行'}，轮流落子`}</li>
            <li>先形成五子连珠者获胜</li>
            <li>{gameMode === 'pvp' ? '可以悔棋，重新开始游戏' : '可悔棋两步，重新开始游戏'}</li>
          </ul>
        </div>
      </div>
    </div>
  )
}

export default App
